<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/13
 * Time: 17:59
 */

namespace App\Http\Controllers;
use App\Models\RecommandUser;
use App\Models\RecommandList;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;


class RecommandController extends Controller
{
    public function __construct() {
        $this->listModel    = new RecommandList();
        $this->RecommandUser = new RecommandUser();
        $this->sessionData = [];
        $this->middleware(function ($request,$next) {
            $this->sessionData = $request->session()->get('eai');
            return  $next($request);
        });        
    }
    // 推荐榜
    public function recommenDetails(Request $request){
        //推荐列表
        $recomanalyst = DB::table("waihui_tuijian_list as al")
                            ->join("waihui_tuijian_user as u",'al.tuijian_id','u.id')
                            ->join("waihui_member as m",'m.id','u.userid')
                            ->select("al.*",'u.userid','u.nickname','m.photo as mphoto')
                            ->where([["al.status",'=',1]])
                            ->orderBy('upvotes','desc')
                            ->orderBy("time",'desc')
                            ->paginate(10);
        foreach ($recomanalyst as $k=>$v){
            $analystarr = DB::table("waihui_member")
                            ->whereIn('id',explode(',',$v->analyst_id))
                            ->select('username', 'photo','id')->get()->toArray();
            $recomanalyst[$k]->analysts  = $analystarr;
            $analysname = [];
            $analysphoto= [];
            $analysid   = [];
            foreach ($analystarr as $anv){
                $analysname[]  = $anv->username;
                $analysphoto[] = $anv->photo;
                $analysid[]    = $anv->id;
            }
            $recomanalyst[$k]->analysnames   = implode(',',$analysname);
            $recomanalyst[$k]->analysphotos  = implode(',',$analysphoto);
            $recomanalyst[$k]->analysids     = implode(',',$analysid);
            $recomanalyst[$k]->fangxiang     = explode(',',$v->direction);
            $recomanalyst[$k]->follownum     = DB::table("waihui_follow")
//                                                  ->where([['status','=',1]])
                                                    ->whereIn('analyst_id',explode(',',$v->analyst_id))
                                                    ->value(DB::raw("Count(id)"));
        }
//        dd($recomanalyst);
        //获取正在订阅的分析师
        $subanalyst   = [];
        if($this->sessionData){
            $subanalyst   = DB::table('waihui_follow as f')
                                ->join("waihui_member as m",'f.analyst_id','m.id')
                                ->select('f.analyst_id','m.username','f.direction','m.photo')
                                ->where([['follower_id','=',$this->sessionData['id']],['status','=',1]])
                                ->get()->toArray();
        }
        return view('recommend.recommend',compact('recomanalyst','subanalyst'));
    }
    
    // 列表页
    public function recommenList(Request $request){
        return view('recommend.recommlist');
    }
    // 移动端详情页
    public function mRecommDetail(){
        return view('recommend.recommdatails');
    }
    
//    public function recommendCenter(Request $request){
//        $id = $request->get('id');
//        
//        return view('recommend.recommendcenter');
//    }
    
    // 数据分析师中心页 、个人中心--历史发布
    public  function recommendCenter(Request $request){
        $id = intval($request->get('id'));
        if($id == 0 || $id == ''){
            return redirect('login');
        }
        //获取分析师的基本信息
        $userInfo = $this->getUserInfo($id);
        if(count($userInfo) <= 0){
            return redirect('login');
        }
        
        //判断是否发布过推荐榜单文章
        $userData = $this->RecommandUser->isSetNickName($id);
        if(count($userData) <= 0){
            dd('该分析师没有发布文章');
            return false;
        }
      
        //该分析师发布过的文章  ** start **
        $RecommandList = [];
        $userid = '';
        $pageSize = 5;
        $RecommandList = $this->RecommandUser->history($id,$pageSize);
        
        foreach($RecommandList as &$val){
            $val['userPhoto'] = $userInfo->photo;
            $val['everyFollowCount'] = $this->listModel->contentFollow($val['listid']);
            $userid   = explode(',',$val['analyst_id']);
            $recommandAnalyst = DB::table('waihui_member')->select('id','username','photo')->whereIn('id',$userid)->get()->toArray();
            $direction   = explode(',',$val['direction']);
            array_walk($recommandAnalyst,function (&$v, $k) use ($direction) { $v->direction = $direction[$k]; });
            $val['analystInfo'] = $recommandAnalyst;
            $val['photo'] = explode(',', $val['photo']);
            unset($val['direction']);
            unset($val['analyst_id']);
        }   
        
       
        //该分析师发布过的文章  ** end **
        $userInfo->count = $this->listModel->allCountContent($userData['id']); //获取发布文章总数
        $userInfo->allUpvotes = $this->listModel->allUpvotes($userData['id']);      //获取总订阅人数
        $userInfo->followCount = $this->listModel->countFollow($userData['id']);
//        dd($RecommandList);
        return view('recommend.recommendhistory',  compact('RecommandList','id','userInfo'));
    }
    
    //相关搜索分析师名字
    public function selectUser(Request $res){
        if($res->ajax()){
            $firstLetter = trim($res->get('firstLetter'));
            if($firstLetter == ''){ 
                return json_encode(array('status'=>0,'msg'=>'请输入要搜索的字符'));
            }
            $usernameData = DB::table('waihui_member')->select('username','id','photo')->where('username','like',"$firstLetter%")->get()->toArray();
            return $usernameData;
        }
    }
    //点赞
    public function upvotes(Request $request){
        $id     = intval(trim($request->id));
        $istrue = DB::table("waihui_tuijian_list")->where('id',$id)->increment('upvotes', 1);
        if($istrue){
            return json_encode(array("status"=>1));
        }else{
            return json_encode(array("status"=>0));
        }
    }
    
    //获取分析师的头像、地区、推荐昵称等
    public function getUserInfo($userid){
        $userInfo = DB::table('waihui_member as m')
                    ->join('waihui_member_info as i','m.id','i.userid')
                    ->join('waihui_tuijian_user as u','m.id','u.userid')
                    ->select('u.nickname','m.photo','province','city','country','u.intro','m.tel')
                    ->where('m.id',$userid)
                    ->first();  
        return $userInfo;
    }
    
    //设置和编辑  推荐页昵称等信息
    public function setTuijianNickName(Request $request){
        if($request->ajax()){
            $userid   = $this->sessionData['id'];
            $nickname = trim($request->get('nickname'));
            $intro    = trim($request->get('intro'));
            $type     = intval($request->get('type'));
            if($nickname == '' || $intro == ''){
                return json_encode(array('code'=>0,'msg'=>'昵称和简介都不能为空'));
            }else{
                $code = $this->RecommandUser->checkNameHasExist($nickname);
                if($code != 1 && $code != $userid){ //表示昵称已被占用，判断是不是自己占用(修改时用此判断)
                    return json_encode(array('code'=>1,'msg'=>'昵称已被占用'));
                }
                if($type == 1){ //如果是第一次填写资料
                    $res = DB::table('waihui_tuijian_user')->insert(['nickname'=>$nickname,'intro'=>$intro,'userid'=>$userid]);
                }else if($type == 2){ //如果是编辑资料
                    $res = DB::table('waihui_tuijian_user')->where('userid',$userid)->update(['nickname'=>$nickname,'intro'=>$intro]);
                }
                if($res == 1){
                    if($type == 1){
                        return json_encode(array('code'=>2,'msg'=>'设置成功'));
                    }else{
                        return json_encode(array('code'=>2,'msg'=>'修改成功'));
                    }
                   
                }else{
                    if($type == 1){
                        return json_encode(array('code'=>2,'msg'=>'设置失败'));
                    }else{
                        return json_encode(array('code'=>2,'msg'=>'修改失败'));
                    }
                }
               
            }
        }
    }
    //添加推荐榜单
    public function addRecommand(Request $request){
        if(count($this->sessionData) < 0){
            return json_encode(array('code'=>0,'msg'=>'请先登录'));
        }
        if($request->ajax()){
            $direction  = $request->get('FenArrFang');
            $analyst_id = array_unique($request->get('FenArrId'));
            $imgs = $request->get('Img');
            if(count($direction) != 3 || count($analyst_id) != 3 || count($imgs) != 3){
                return json_encode(array('code'=>0,'msg'=>'参数有误'));
            }
            $userData = $this->RecommandUser->isSetNickName($this->sessionData['id']);
            $data['tuijian_id'] = $userData['id'];
            $data['direction']  = implode(',',$direction);
            $data['analyst_id'] = implode(',',$analyst_id);
            $data['photo']      = implode(',',$imgs);
            $data['content']    = trim($request->get('textCon'));
            $data['time']       = time();
            $listid              = intval(trim($request->get("listid")));
            if($listid){
                //判断此推荐是否为本人的
                $isexist = DB::table('waihui_tuijian_list as l')
                                ->join("waihui_tuijian_user as u",'l.tuijian_id','u.id')
                                ->where([['l.id','=',$listid],['u.userid','=',$this->sessionData['id']]])->first();
                if($isexist){
                    $res = DB::table('waihui_tuijian_list')->where('id',$listid)->update($data);
                }else{
                    return json_encode(array('code'=>0,'msg'=>'非法操作'));
                }
            }else{
                $res = DB::table('waihui_tuijian_list')->insert($data);
            }

            if($res){
                return json_encode(array('code'=>1,'msg'=>'操作成功'));
            }else{
                return json_encode(array('code'=>0,'msg'=>'操作失败'));
            }

        }

    }

    //删除发布推荐信息
    public function delRecommendByID(Request $request){
        if(count($this->sessionData) < 0){
            return json_encode(array('status'=>2,'msg'=>'请先登录'));
        }
        $id     = intval(trim($request->id));
        $result = DB::table("waihui_tuijian_list")->where("id",$id)->update(array('status'=>2));
        if($result){
            return json_encode(array("status"=>1,'msg'=>"删除成功"));
        }else{
            return json_encode(array("status"=>0,'msg'=>"删除失败"));
        }
    }
    
}    
